package com.mao.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class SimpleNotepad extends JFrame {
    private JTextArea textArea;
    private JFileChooser fileChooser;
    private File currentFile;
    private boolean unsavedChanges = false;

    public SimpleNotepad() {
        initUI();
    }

    private void initUI() {
        // 初始化文本区域
        textArea = new JTextArea();
        textArea.setFont(new Font("宋体", Font.PLAIN, 14));
        textArea.getDocument().addDocumentListener(new SimpleDocumentListener(() -> {
            unsavedChanges = true;
        }));

        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane);

        // 初始化菜单栏
        JMenuBar menuBar = new JMenuBar();
        initFileMenu(menuBar);
        initEditMenu(menuBar);
        initFormatMenu(menuBar);
        initHelpMenu(menuBar);
        setJMenuBar(menuBar);

        // 窗口设置
        setTitle("简易记事本");
        setSize(800, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                //checkUnsavedChanges();
                checkUnsavedChanges(() -> dispose());
            }
        });
    }

    private void initFileMenu(JMenuBar menuBar) {
        JMenu fileMenu = new JMenu("文件");

        addMenuItem(fileMenu, "新建", KeyEvent.VK_N, this::newFile); //
        addMenuItem(fileMenu, "打开", KeyEvent.VK_O, this::openFile);
        addMenuItem(fileMenu, "保存", KeyEvent.VK_S, this::saveFile);
        addMenuItem(fileMenu, "另存为", 0, this::saveAsFile);
        fileMenu.addSeparator();
        addMenuItem(fileMenu, "退出", KeyEvent.VK_Q, this::exitApp);

        menuBar.add(fileMenu);
    }

    private void initEditMenu(JMenuBar menuBar) {
        JMenu editMenu = new JMenu("编辑");

        addMenuItem(editMenu, "复制", KeyEvent.VK_C, () -> textArea.copy());
        addMenuItem(editMenu, "粘贴", KeyEvent.VK_V, () -> textArea.paste());
        addMenuItem(editMenu, "剪切", KeyEvent.VK_X, () -> textArea.cut());

        menuBar.add(editMenu);
    }

    private void initFormatMenu(JMenuBar menuBar) {
        JMenu formatMenu = new JMenu("格式");
        addMenuItem(formatMenu, "字体", 0, this::setFont);
        menuBar.add(formatMenu);
    }

    private void initHelpMenu(JMenuBar menuBar) {
        JMenu helpMenu = new JMenu("帮助");
        addMenuItem(helpMenu, "关于", 0, this::showAbout);
        menuBar.add(helpMenu);
    }

    private void addMenuItem(JMenu menu, String text, int keyCode, Runnable action) {
        JMenuItem item = new JMenuItem(text);
        item.setAccelerator(KeyStroke.getKeyStroke(keyCode, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
        item.addActionListener(e -> action.run());
        menu.add(item);
    }

    private void newFile() {
        checkUnsavedChanges(() -> {
            textArea.setText("");
            currentFile = null;
            unsavedChanges = false;
            setTitle("简易记事本");
        });
    }

    private void openFile() {
        checkUnsavedChanges(() -> {
            if (fileChooser == null) {
                fileChooser = new JFileChooser();
            }
            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                try {
                    currentFile = fileChooser.getSelectedFile();
                    textArea.read(new FileReader(currentFile), null);
                    unsavedChanges = false;
                    setTitle(currentFile.getName() + " - 简易记事本");
                } catch (IOException ex) {
                    showError("打开文件失败");
                }
            }
        });
    }

    private void saveFile() {
        if (currentFile == null) {
            saveAsFile();
        } else {
            try (FileWriter writer = new FileWriter(currentFile)) {
                textArea.write(writer);
                unsavedChanges = false;
            } catch (IOException ex) {
                showError("保存文件失败");
            }
        }
    }

    private void saveAsFile() {
        if (fileChooser == null) {
            fileChooser = new JFileChooser();
        }
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            currentFile = fileChooser.getSelectedFile();
            saveFile();
            setTitle(currentFile.getName() + " - 简易记事本");
        }
    }

    private void setFont() {
        Font currentFont = textArea.getFont();
        JFontChooser fontChooser = new JFontChooser();
        fontChooser.setSelectedFont(currentFont);
        if (fontChooser.showDialog(this) == JFontChooser.OK_OPTION) {
            textArea.setFont(fontChooser.getSelectedFont());
        }
    }

    private void showAbout() {
        JOptionPane.showMessageDialog(this,
                "简易记事本\n版本 1.0\n作者：Your Name",
                "关于",
                JOptionPane.INFORMATION_MESSAGE);
    }

    private void exitApp() {
        checkUnsavedChanges(this::dispose);
    }

    private void checkUnsavedChanges(Runnable onContinue) {
        if (unsavedChanges) {
            int result = JOptionPane.showConfirmDialog(this,
                    "当前文件未保存，是否保存？",
                    "未保存的更改",
                    JOptionPane.YES_NO_CANCEL_OPTION);

            if (result == JOptionPane.YES_OPTION) {
                saveFile();
                onContinue.run();
            } else if (result == JOptionPane.NO_OPTION) {
                onContinue.run();
            }
        } else {
            onContinue.run();
        }
    }

    private void showError(String message) {
        JOptionPane.showMessageDialog(this,
                message,
                "错误",
                JOptionPane.ERROR_MESSAGE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new SimpleNotepad().setVisible(true);
        });
    }

}

// 简单的字体选择对话框（需要自行实现或使用第三方库）
class JFontChooser extends JDialog {
    // 实现字体选择逻辑（此处需要具体实现）
    // 这里只是一个占位实现
    public Font getSelectedFont() { return Font.getFont(Font.SANS_SERIF); }
    public void setSelectedFont(Font font) {}
    public static int OK_OPTION = 0;
    public int showDialog(Component parent) { return OK_OPTION; }
}

// 文档修改监听器
class SimpleDocumentListener implements javax.swing.event.DocumentListener {
    private final Runnable callback;

    public SimpleDocumentListener(Runnable callback) {
        this.callback = callback;
    }

    @Override
    public void insertUpdate(javax.swing.event.DocumentEvent e) { callback.run(); }
    @Override
    public void removeUpdate(javax.swing.event.DocumentEvent e) { callback.run(); }
    @Override
    public void changedUpdate(javax.swing.event.DocumentEvent e) { callback.run(); }

}